package com.wenx.concurrent.producerconsumer;

/**
 * Created by wenx on 2019-10-18 14:58
 */
public class Table {

    private final String[] buffer;

    private int tail;

    private int head;

    private int count;

    public Table(int count) {
        this.buffer = new String[count];
        this.tail = 0;
        this.head = 0;
        this.count = 0;
    }

    public synchronized void put(String cake) {
        System.out.println(Thread.currentThread().getName() + " put " + cake);
        while (count >= buffer.length) {
            try {
                //等候
                wait();
            } catch (InterruptedException e) {
                System.out.println("中断异常1" +e.getMessage());
            }
        }
        buffer[tail++] = cake;
        count++;
        if(tail == buffer.length) {
            tail = 0;
        }
        notifyAll();
    }

    public synchronized String take() {
        while (count == 0) {
            try {
                wait();
            } catch (InterruptedException e) {
                System.out.println("中断异常2" +e.getMessage());
            }
        }
        String cake = buffer[head++];
        //head = (head +1) % buffer.length;
        if(head == buffer.length) {
            head = 0;
        }
        count--;
        notifyAll();
        System.out.println(Thread.currentThread().getName() + " takes " + cake);
        return cake;
    }
}